Python is a great programming language and with the help of a few popular libraries such numpy and matplotlib it becomes a powerful environment for Linear Algebra computing.
Numpy Documentation - This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the numpy reference to find out much more about numpy.
Rectangulare array of numbers
In [221]:
import numpy as np
In [222]:
# Create a rank 1 array
a = np.array(
[
[1,2,3,4],
[1,4,5,6],
[1,2,3,4]
]
)
print (a)
print (type(a))
print (a.shape)
In [223]:
a = np.array(
[
[1,2,3,4],
[1,4,5,6],
[1,2,3,4]
])
print (a)
a[0,0] = 100
print ()
print (a)
Datatypes
In [224]:
a = np.array(
[
[1,2,3,4],
[1,4,5,6],
[1,2,3,4]
]
)
print (a)
print (type(a[0,0]))
print ()
a = np.array(
[
[1.2,2,3,4],
[1,4,5,6],
[1,2,3,4]
]
)
print (a)
print (type(a[0,0]))
Compute sum of all elements in matrix
In [225]:
x = np.array([
[1,2,1],[3,4,1]])
print (x)
print (np.sum(x))
print (np.sum(x, axis=0))
print (np.sum(x, axis=1))
Create an array of all zeros
In [226]:
a = np.zeros((4,4))
a
Out[226]:
Create an array of all ones
In [227]:
a = np.ones((2,5))
a
Out[227]:
Create a constant array
In [228]:
a = np.full((4,4), 7)
a
Out[228]:
Create an identity matrix
In [229]:
a = np.eye(4)
a
Out[229]:
Create an array filled with random values
In [230]:
a = np.random.random((5,5))
a
Out[230]:
slicing to pull out the subarray
In [231]:
a = np.array(
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
])
print (a)
print ()
b = a[:1, :3]
print (b)
In [232]:
x = np.ones((4,7))
print (x)
y = np.full((4,7), 4.3)
print (y)
z = x+y
print ()
print (z)
In [233]:
x = np.array(
[
[1.2,2,3,4],
[1,4,5,6],
[1,2,3,4]
])
print (x)
y = np.array(
[
[1,2,3,4],
[1,4,5,6],
[1,2,3,4]
])
print (y)
print ()
z = np.add(x, y)
print (z)
In [234]:
z = x - y
print (z)
print ()
z = np.subtract(x, y)
print (z)
In [235]:
x = np.array(
[
[1,0,-1],
[1,2,-1],
[1,0,-1],
[1,0,-1]
])
print (x)
y = np.array([1,1,2])
print (y)
z = np.dot(x, y)
print (z)
In [236]:
x = np.array(
[
[1,2,3],
[4,5,6]
])
print (x)
y = np.array(
[
[7,8],
[9,10],
[11,12]
])
print (y)
print ()
z = np.dot(x, y)
print (z)
print ()
z = np.dot(y, x)
print (z)
In [237]:
x = np.array([[0,1,2,0], [0,3,4,5]])
print (x)
print ()
print (x.T)
Note that taking the transpose of a rank 1 array does nothing
In [238]:
x = np.array([0,1,2,3])
print (x)
print (x.shape)
y = x.T
print (y.shape)
Create an empty matrix with the same shape as x
In [240]:
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print (x)
print ()
v = np.array([1, 5, 1])
y = np.empty_like(x)
for i in range(4):
y[i, :] = x[i, :] + v
print (y)
In [ ]: